package org.crc.myvhrb.service;

import org.crc.myvhrb.mapper.MenuMapper;
import org.crc.myvhrb.mapper.MenuRoleMapper;
import org.crc.myvhrb.model.Hr;
import org.crc.myvhrb.model.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * CRC
 * 2021/8/3
 */
@Service
public class MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    MenuRoleMapper menuRoleMapper;

    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }


    public List<Menu> getMenusByHrId() {
        return menuMapper.getMenusByHrId(((Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
    }

    @Cacheable(cacheNames = "vh1")
    public List<Menu> getAllMenusWithRole() {
       return menuMapper.getAllMenusWithRole();
    }

    public List<Integer> getMidsByRid(Integer rid) {
        return menuMapper.getMidsByRid(rid);
    }

    /**
     *  更新操作逻辑：
     *  首先根据角色ID rid 删除所有角色权限数据
     *  其次在通过 权限ID mid 添加角色数据
     *  不采用直接更新的方式
     * @param rid
     * @param mids
     * @return
     */
    @Transactional
    public boolean updateMenuRole(Integer rid, Integer[] mids) {
        // 根据 rid 清空数据
        menuRoleMapper.deleteByRid(rid);
        // 如果 更新的 mid 为空，则不进行插入操作
        if (mids == null || mids.length == 0){
            return true;
        }
        Integer result = menuRoleMapper.insertRecord(rid,mids);
        // 判断是否全部更新完成
        return result==mids.length;
    }
}
